﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Opc.Ua.Sample.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Opc.Ua.Client.Controls
{
    public partial class BindVarDlg : Form
    {
        string m_strOpcServer = "";
        List<string> m_NodeIDList = null;
        List<string> m_varNamesList = null;

        private static IniFile m_iniFile = new IniFile(Application.StartupPath + "\\Hzhehua.ini");

        public BindVarDlg(string strOpcServer, List<string> nodeList, List<string> varNamesList)
        {
            m_NodeIDList = nodeList;
            m_strOpcServer = strOpcServer;
            m_varNamesList = varNamesList;

            InitializeComponent();
        }

        void InitdataGridView()
        {
            dataGridView_BindVar.Columns.Clear();
            {
                {
                    DataGridViewTextBoxColumn acCode = new DataGridViewTextBoxColumn();
                    acCode.HeaderText = "Opc变量";
                    acCode.Width = 600;
                    acCode.ReadOnly = true;
                    acCode.SortMode = DataGridViewColumnSortMode.NotSortable;
                    dataGridView_BindVar.Columns.Add(acCode);
                }
                {
                    DataGridViewTextBoxColumn acCode = new DataGridViewTextBoxColumn();
                    acCode.HeaderText = "自定义变量";
                    acCode.Width = 300;
                    acCode.ReadOnly = false;
                    acCode.SortMode = DataGridViewColumnSortMode.NotSortable;
                    dataGridView_BindVar.Columns.Add(acCode);
                }
                {
                    DataGridViewCheckBoxColumn acCode = new DataGridViewCheckBoxColumn();
                    acCode.HeaderText = "是否保存";
                    acCode.Width = 100;
                    acCode.ReadOnly = false;
                    acCode.SortMode = DataGridViewColumnSortMode.NotSortable;
                    dataGridView_BindVar.Columns.Add(acCode);
                }


                dataGridView_BindVar.AllowUserToAddRows = false;
            }
        }

        void AddOpcData()
        {
            dataGridView_BindVar.Rows.Clear();

            for (int i=0;i<m_NodeIDList.Count;i++)
            {
                dataGridView_BindVar.Rows.Add();
                dataGridView_BindVar.Rows[i].Cells[0].Value = m_NodeIDList[i];
                dataGridView_BindVar.Rows[i].Cells[1].Value = m_varNamesList[i];
                dataGridView_BindVar.Rows[i].Cells[2].Value = true;
            }
        }

        private void BindVarDlg_Load(object sender, EventArgs e)
        {
            InitdataGridView();

            AddOpcData();

            textBox_OpcServer.Text = m_strOpcServer;
        }

        private void button_Close_Click(object sender, EventArgs e)
        {
            Close();
        }


        private void Save2CfgFile()
        {
            try
            {
                File.Delete(m_iniFile.m_strIniPath);
            }
            catch(Exception)
            { }

            m_iniFile.writeString("OpcServerParam","OpcServer", m_strOpcServer);

            // 循环行
            for (int count = 0; count < dataGridView_BindVar.Rows.Count; count++)
            {
                if ((bool)dataGridView_BindVar.Rows[count].Cells[2].EditedFormattedValue == true)
                {
                    m_iniFile.writeString("OpcServerParam", dataGridView_BindVar.Rows[count].Cells[1].Value.ToString(), dataGridView_BindVar.Rows[count].Cells[0].Value.ToString());
                }
            }
        }

        private void button_OK_Click(object sender, EventArgs e)
        {
            if (dataGridView_BindVar.RowCount < 1)
            {
                return;
            }

            TableToExcel(GetDgvToTable(dataGridView_BindVar), Application.StartupPath + "\\Hzhehua.xls");

            Save2CfgFile();

            MessageBox.Show("保存成功");
            //if (textBox_UserVar.Text.Length < 1)
            //{
            //    MessageBox.Show("请输入变量名");
            //     return;
            //}
            //m_iniFile.writeString("OpcVar", textBox_UserVar.Text, m_strNodeID);
            //m_iniFile.writeString(textBox_UserVar.Text,"OpcVar", m_strNodeID);
            //m_iniFile.writeString(textBox_UserVar.Text,"OpcServer", m_strOpcServer);

            //string strTmp = m_iniFile.readString("OpcVar", textBox_UserVar.Text, "");

            //Close();
        }

        private void button_del_Click(object sender, EventArgs e)
        {
            try
            {
                //选中的行数
                int iCount = dataGridView_BindVar.SelectedRows.Count;
                if (iCount < 1)
                {
                    return;
                }
                if (DialogResult.Yes == MessageBox.Show("是否删除选中的数据？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
                {
                    for (int i = this.dataGridView_BindVar.SelectedRows.Count; i > 0; i--)
                    {
                        dataGridView_BindVar.Rows.RemoveAt(dataGridView_BindVar.SelectedRows[i - 1].Index);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("删除失败");
            }
        }

        private void dataGridView_BindVar_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dataGridView_BindVar.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView_BindVar.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView_BindVar.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }


        /// <summary>
        /// Datable导出成Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file">导出路径(包括文件名与扩展名)</param>
        public void TableToExcel(DataTable dt, string file)
        {
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
            if (workbook == null) { return; }
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);

            //OPC服务器地址。
            {
                IRow row2 = sheet.CreateRow(0);
                ICell cell = row2.CreateCell(0);
                cell.SetCellValue("OPC服务器地址 ");
                cell = row2.CreateCell(1);
                cell.SetCellValue(m_strOpcServer);

                //
                row2 = sheet.CreateRow(1);
                row2 = sheet.CreateRow(2);
                row2 = sheet.CreateRow(3);
            }

            //表头  
            IRow row = sheet.CreateRow(4);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            //数据  
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 5);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            //转为字节数组  
            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件  
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private  object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        /// <summary>
        /// 绑定DataGridView数据到DataTable
        /// </summary>
        /// <param name="dgv">复制数据的DataGridView</param>
        /// <returns>返回的绑定数据后的DataTable</returns>
        public DataTable GetDgvToTable(DataGridView dgv)
        {
            DataTable dt = new DataTable();
            // 列强制转换
       //     for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn("OPC 变量名");
                dt.Columns.Add(dc);
            }
            {
                DataColumn dc = new DataColumn("自定义变量名");
                dt.Columns.Add(dc);
            }

            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                if ((bool)dgv.Rows[count].Cells[2].EditedFormattedValue == true)
                {
                    DataRow dr = dt.NewRow();
                    for (int countsub = 0; countsub < dgv.Columns.Count-1; countsub++)
                    {
                        dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
    }
}
